package com.qst.order.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qst.order.domain.Cart;
import com.qst.order.domain.DTO.CartDeleteRequest;
import com.qst.order.service.CartService;
import com.qst.order.service.UserService;
import com.qst.order.utils.JwtUtil;
import com.qst.order.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/cart")
@RequiredArgsConstructor
public class CartController {

    private final CartService cartService;

    private final ObjectMapper objectMapper;
    private final JwtUtil jwtUtil;



    @PostMapping("/add")
    public Result addCart(@RequestBody Cart cart , @RequestHeader("Authorization") String token) {
        log.info("加入购物车{}",cart);

        String userId = jwtUtil.getClaim(token, "userId");

        if (cart.getSpecsTemp() != null) {
            try {
                String specsStr = objectMapper.writeValueAsString(cart.getSpecsTemp());
                cart.setSpecs(specsStr); // 存入字符串
            } catch (JsonProcessingException e) {
                log.error("转换规格为JSON失败", e);
                return Result.error("规格格式错误");
            }
        }

        List<Cart> list = cartService.lambdaQuery().eq(Cart::getUserId, userId).
                list();
        if (!list.isEmpty()) {
            for (Cart c : list) {
                if (c.getProductId().equals(cart.getProductId())) {
                    return Result.error("购物车已存在此商品");
                }
            }
        }
        boolean b = cartService.addCart(cart,Integer.parseInt(userId));

        if (!b) {
            return Result.error("添加购物车失败");
        }
        return Result.success("添加购物车成功");

    }



    @GetMapping("/list")
    public Result list(@RequestHeader("Authorization") String token) {
        // 1. 获取用户ID（你的原有逻辑）
        String userId = jwtUtil.getClaim(token, "userId");

        // 2. 查询购物车列表（此时specs是JSON字符串）
        List<Cart> cartList = cartService.lambdaQuery()
                .eq(Cart::getUserId, userId)
                .list();

        // 3. 手动解析JSON字符串为Map
        for (Cart cart : cartList) {
            String specsJson = cart.getSpecs();  // 获取原始JSON字符串
            if (specsJson == null || specsJson.trim().isEmpty() || "null".equals(specsJson)) {
                cart.setSpecsMap(new HashMap<>());  // 空值处理
                continue;
            }

            try {
                // 解析JSON为Map
                Map<String, String> specsMap = objectMapper.readValue(
                        specsJson,
                        new TypeReference<Map<String, String>>() {}  // 明确Map类型
                );
                cart.setSpecsMap(specsMap);
            } catch (JsonProcessingException e) {
                // 解析失败时的容错处理
                log.error("解析规格JSON失败: {}", specsJson, e);
                cart.setSpecsMap(new HashMap<>());  // 解析失败时设为空Map
            }
        }

        return Result.success(cartList);
    }


    @DeleteMapping("/deleteBatch")//删除结算的id集合
    public Result delete(@RequestBody CartDeleteRequest cartIds, @RequestHeader("Authorization") String token) {

        log.info("删除购物车:{}", cartIds);


        boolean b = cartService.deleteBatch(cartIds.getCartIds(),Integer.parseInt(jwtUtil.getClaim(token, "userId")));

        if (!b) {
            return Result.error("删除购物车失败");
        }
        return Result.success();
    }

}
